package com.watereast.crawler2;

import org.springframework.util.Assert;

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;

public class DigestUtil2 {

    private static PrivateKey loadPrivateKey(String priStr) {
        Assert.hasText(priStr, "priStr");
        try {
            byte[] keyBytes = Base64.getDecoder().decode(priStr);
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
            return privateKey;
        } catch (Exception e) {
            throw new RuntimeException("出错啦", e);
        }
    }

    public static String privateDecrypt(String content, String privateKey, boolean hexOrBase64) {
        Assert.notNull(content, "content");
        Assert.notNull(privateKey, "privateKey");
        try {
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(2, loadPrivateKey(privateKey));
            if (hexOrBase64) {
                return new String(cipher.doFinal(hex2bytes(content)));
            }
            return new String(cipher.doFinal(decodeBase64(content)));
        } catch (Exception e) {
            throw new RuntimeException("出错啦", e);
        }
    }

    public static byte[] hex2bytes(String hexStr) {
        Assert.hasText(hexStr, "hexStr");
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

    public static byte[] decodeBase64(String text) {
        Assert.hasText(text, "text");
        return Base64.getDecoder().decode(text);
    }
}
